package com.frogs.ucenter.service.impl;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.file.FileUtil;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.web.api.entity.ApiUrl;
import com.frogs.ucenter.entity.UserBaseAccountInfo;
import com.frogs.ucenter.service.AbsService;
import com.frogs.ucenter.service.UploadService;

@Service("uploadService")
public class UploadServiceImpl extends AbsService implements UploadService {
	
	private static Logger log = LoggerFactory.getLogger(UploadServiceImpl.class);

	@Override
	public JSONObject uploadImage(HttpServletRequest request, UserBaseAccountInfo user) {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_IMG_UPLOAD");
		PostMethod post = new PostMethod(apiUrl.getUrl());
		HttpClient httpclient = new HttpClient();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

		Map<String, MultipartFile> files = multipartRequest.getFileMap();
		List<Part> partsList = new ArrayList<Part>();
		List<File> fileList = new ArrayList<File>();
		
		partsList.add(new StringPart(ApiUrlParamEnum.resourceId.getParamName(), String.valueOf(user.getId())));
		partsList.add(new StringPart(ApiUrlParamEnum.refResource.getParamName(), "user"));
		partsList.add(new StringPart(ApiUrlParamEnum.userId.getParamName(), String.valueOf(user.getId())));
		partsList.add(new StringPart(ApiUrlParamEnum.accountName.getParamName(), user.getAccountName()));
		partsList.add(new StringPart(apiUrl.getKeyvals()[0], apiUrl.getKeyvals()[1]));
		partsList.add(new StringPart(apiUrl.getKeyvals()[2], apiUrl.getKeyvals()[3]));
		
		try {
			for (Entry<String, MultipartFile> entity : files.entrySet()) {
				MultipartFile multipartFile = entity.getValue();
				String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
				String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
				String filePath = FileUtil.getSaveFilePath(FileUtil.getRealPath(request), "/upload/images",  fileName);;
				
				File file = new File(filePath);
				multipartFile.transferTo(file);
				FilePart part = new FilePart(entity.getKey(), file);
				partsList.add(part);
				fileList.add(file);
			}

			Part[] parts = partsList.toArray(new Part[partsList.size()]);
			HttpMethodParams param = new HttpMethodParams();
			MultipartRequestEntity entity = new MultipartRequestEntity(parts, param);
			post.setRequestEntity(entity);
			httpclient.executeMethod(post);
			
			InputStream in = post.getResponseBodyAsStream();
			StringBuffer out = new StringBuffer();
			byte[] b = new byte[512];
			for (int n; (n = in.read(b)) != -1;) {
				out.append(new String(b, 0, n));
			}
			JSONObject resultJson = JSONObject.parseObject(out.toString());
			return resultJson;
		} catch (Exception e) {
			log.error("上传参数失败", e);
		} finally {
			if(fileList.size() != 0) {
				for(File f : fileList) {
					f.delete();
				}
			}
		}
		
		return null;
	}

	


}
